package com.zzw.easyexcel;

import com.alibaba.excel.write.handler.WriteHandler;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @author Administrator
 */
public class DefaultEasyExcel implements EasyExcel {

    private void buildResponseHeader(HttpServletResponse httpServletResponse, String excelName) {
        httpServletResponse.setContentType("application/vnd.ms-excel");
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(excelName, StandardCharsets.UTF_8) + ".xlsx");
    }

    @Override
    public void write(HttpServletResponse httpServletResponse, String excelName, List<List<String>> head, String sheetName, List<List<Object>> data) throws IOException {
        buildResponseHeader(httpServletResponse, excelName);
        com.alibaba.excel.EasyExcel.write(httpServletResponse.getOutputStream()).head(head).sheet(sheetName).doWrite(data);
    }

    @Override
    public void write(HttpServletResponse httpServletResponse, String excelName, List<List<String>> head, String sheetName, List<List<Object>> data, WriteHandler writeHandler) throws IOException {
        buildResponseHeader(httpServletResponse, excelName);
        com.alibaba.excel.EasyExcel.write(httpServletResponse.getOutputStream()).head(head).sheet(sheetName)
                .registerWriteHandler(writeHandler).doWrite(data);
    }

    @Override
    public void write(HttpServletResponse httpServletResponse, String excelName, List<List<String>> head, String sheetName, List<List<Object>> data, WriteHandler writeHandler, WriteHandler rowWriteHandler) throws IOException {
        buildResponseHeader(httpServletResponse, excelName);
        com.alibaba.excel.EasyExcel.write(httpServletResponse.getOutputStream()).head(head).sheet(sheetName)
                .registerWriteHandler(writeHandler).registerWriteHandler(rowWriteHandler).doWrite(data);
    }
}
